const dbUtils = require('../utils/db-util');

const category = {

	/**
	 * 增加分类
	 * @param  {object} model 消息数据模型
	 * @return {object}       mysql执行结果
	 */
	async addCategory(model, parentId) {
		if(!parentId) {
			parentId = 0;
		}
		let _sql = `
			insert into category set name = "${model.name}",
				parent_id = ${parentId},
				create_time = ${model.create_time},
				update_time = ${model.update_time}`;
		let result = await dbUtils.query(_sql);
		if(result && result.insertId) {
			result = result;
		} else {
			result = null;
		}
		return result;
	},

	/**
	 * 获取分类
	 * @param  {object} model 消息数据模型
	 * @return {object}       mysql执行结果
	 */
	async getCategory(model) {
		let _sql = `
			select * from category where 1=1`;
		if(model.id) {
			_sql += ` and id = ${model.id}`;
		}
		if(model.name) {
			_sql += ` and name = "${model.name}"`;
		}
		if(model.parent_id) {
			_sql += ` and parent_id = ${model.parent_id}`;
		}
		let result = await dbUtils.query(_sql);
		if(Array.isArray(result) && result.length > 0) {
			result = result;
		} else {
			result = null;
		}
		return result;
	},

	/**
	 * 更新分类
	 * @param  {object} model 消息数据模型
	 * @return {object}       mysql执行结果
	 */
	async updateCategory(model, id) {
		let result = await dbUtils.updateData('category', model, id);
		return result;
	},

	/**
	 * 删除分类
	 * @param  {object} model 消息数据模型
	 * @return {object}       mysql执行结果
	 */
	async deleteCategory(model) {
		let result = await dbUtils.deleteDataById('category', model.id);
		return result;
	},

	/**
	 * 获取热门分类
	 * @param  {object} model 消息数据模型
	 * @return {object}       mysql执行结果
	 */
	async getHotCategory(model) {
		let _sql = `select * from category where is_hot = 1`;
		let result = await dbUtils.query(_sql);
		if(Array.isArray(result) && result.length > 0) {
			result = result;
		} else {
			result = null;
		}
		return result;
	},
};

module.exports = category;